package com.project.util;

import cn.hutool.core.io.resource.FileObjectResource;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class FileUtils {

    /**
     * 将长链接和短链接写入同一行，写入文件
     * @param longUrlList
     * @param shortUrlList
     * @return
     */
    public static byte[] convertToByteArray(List<String> longUrlList, List<String> shortUrlList) throws IOException {
        List<String> mapList = new ArrayList<>();
        // 写入同一个
        for (int i = 0 ; i< longUrlList.size(); i++){
            mapList.add(longUrlList.get(i)+ " " + "http://dwy.cn/"+shortUrlList.get(i));
        }
        // 写入文件
        String newfileName = UUID.randomUUID().toString().replace("-","");
        String filePath = "d:/output/" + newfileName+".txt";
        FileWriter fw=new FileWriter(filePath);
        //写入中文字符时会出现乱码
        BufferedWriter bw=new BufferedWriter(fw);

        for(String arr:mapList){
            bw.write(arr+"\t\n");
        }
        bw.close();
        fw.close();
        // 返回字节数组
        byte[] bytes = toByteArray(filePath);
        return bytes;
    }

    /**
     * 将文件转化为字节数组
     * @param filePath
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray(String filePath) throws IOException {
        InputStream inputStream = new FileInputStream(filePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024 * 4];
        int n = 0;
        while ((n = inputStream.read(bytes)) != -1) {
            baos.write(bytes, 0, n);
        }
        inputStream.close();
        return baos.toByteArray();
    }

}
